package com.kehutong.payment.task;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.coraframework.inject.Singleton;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.orm.Pool;
import com.kehutong.payment.enums.ExcType;

/**
 * 对账定时任务
 */
@Singleton
public class ReconciliateJob{
    // implements Job{

    private Logger logger = LoggerFactory.getLogger(ReconciliateJob.class);

    public static final String appid = "wxee139fabd7eac523";
    public static final String mch_id = "1601487213";
    public static final String mchSecret = "20ac21e6d473c3c10b1d0cb3d5604120";

    // @Inject
    // private PayUrlConfig payConfig;
    // @Inject
    // private SQLSession jdbcSession;

    public  void  reconciliationTask() throws Exception {
        /*PayData data = new ReconciliateData(
                appid,
                mch_id,
                null,
                generateDate(),
                TencentPayResult.SUCCESS.toString()
        );
        data.setSign(data.md5Encode(mchSecret));
        String text = payConfig.send("/pay/downloadbill", http -> {
            http.setBody(data.toXml());
        });
        logger.info(" reconciliation result：*********"+text+"***********");
        String[] arr = text.split("\r\n");
        String[] firstRowDataArr = arr[0].split(",");
        //,分割长度大于1表示有账单，or--返回错误码
        if(firstRowDataArr.length > 1){
            logger.info("=======yesterday has successed charge record=======");
            for (int i = 1; i < arr.length-2; i++) {
                String[] iRowDataArr = arr[i].split(",");
                String outTradeNo =  iRowDataArr[6].replace("`","");
                String payTime = iRowDataArr[0].replace("`", "");
                String billType = iRowDataArr[9].replace("`", "");
                String mchId = iRowDataArr[2].replace("`", "");
                String subMchId = iRowDataArr[3].replace("`", "");
                String transactionId = iRowDataArr[5].replace("`", "");
                String tradeType = iRowDataArr[8].replace("`", "");
                String currency = iRowDataArr[11].replace("`", "");
                String orderAmountDue = iRowDataArr[12].replace("`", "");
                String couponAmount = iRowDataArr[13].replace("`", "");
                String productName = iRowDataArr[14].replace("`", "");
                String fee = iRowDataArr[16].replace("`", "");
                String feeRate = iRowDataArr[17].replace("`", "");
                String orderAmount = iRowDataArr[18].replace("`", "");
                String feeRemark  = iRowDataArr[19].replace("`", "");

                if(Objects.isNull(hasExist(outTradeNo))){
                    createFeeInfo(outTradeNo, transactionId, mchId, subMchId, payTime, tradeType, billType, currency,
                            orderAmountDue,  couponAmount, productName, fee, feeRate, orderAmount, feeRemark);
                }
                ChargeRecord cr = Pool.get(ChargeRecord.class, outTradeNo);
                if(Objects.isNull(cr)){
                    if(Objects.isNull(isExist(outTradeNo))){
                        createReconciliateLog(outTradeNo, true, billType, payTime, ExcType.LOCAL_NONE, mchId, subMchId);
                    }
                }else if(cr.getAmt().compareTo(new BigDecimal(orderAmount)) != 0){
                    if(Objects.isNull(isExist(outTradeNo))){
                        createReconciliateLog(outTradeNo, cr.isResult(), billType, payTime, ExcType.MONEY_NOT_SAME, mchId, subMchId);
                    }
                }else if(!cr.isResult()){
                    if(Objects.isNull(isExist(outTradeNo))){
                        createReconciliateLog(outTradeNo, cr.isResult(), billType, payTime, ExcType.STATUS_NOT_SAME, mchId, subMchId);
                    }
                }
            }
        }else{
            //昨日没有支付的充值记录，或者校验失败
            final JSONObject rs = XmlUtil.xml2JSON(text);
            String error_code = rs.getString("error_code");
            logger.error("reconciliation failed,result is "+rs.toJSONString());
            if(error_code.equals("100") || error_code.equals("20003") || error_code.equals("20100")){
                ReconciliateLog rl = Pool.newInstance(ReconciliateLog.class);
                rl.setExcType(ExcType.SYS_TIME_OUT);
                rl.setRemark(ExcType.SYS_TIME_OUT.getDesc());
                jdbcSession.insert(rl);
            }
        }*/
    }

//    private List<ReconciliateLog> getList(String outTradeNo){
//        return jdbcSession.findArray(ReconciliateLog.class)
//                .eq("outTradeNo", outTradeNo)
//                .exe();
//    }

   /* private ReconciliateLog isExist(String outTradeNo){
        ReconciliateLog rl = Pool.get(ReconciliateLog.class, outTradeNo);
        return rl ;
    }

    private FeeInfo hasExist(String outTradeNo){
        FeeInfo feeInfo = Pool.get(FeeInfo.class, outTradeNo);
        return feeInfo ;
    }

    private void createFeeInfo(String outTradeNo, String transactionId, String mchId, String subMchId, String payTime, String tradeType, String billType, String currency,
                               String orderAmountDue, String couponAmount, String productName, String fee, String feeRate, String orderAmount, String feeRemark){
        FeeInfo fi = Pool.newInstance(FeeInfo.class, outTradeNo);
        fi.setTransactionId(transactionId);
        fi.setMchId(mchId);
        fi.setSubMchId(subMchId);
        fi.setPayTime(Timestamp.valueOf(payTime));
        fi.setTradeType(tradeType);
        fi.setBillType(billType);
        fi.setCurrency(currency);
        fi.setOrderAmountDue(new BigDecimal(orderAmountDue));
        fi.setCouponAmount(new BigDecimal(couponAmount));
        fi.setProductName(productName);
        fi.setFee(new BigDecimal(fee));
        fi.setFeeRate(feeRate);
        fi.setOrderAmount(new BigDecimal(orderAmount));
        fi.setFeeRemark(feeRemark);
        // jdbcSession.insert(fi);
    }

    private void createReconciliateLog(String outTradeNo, boolean result, String billType, String payTime, ExcType excType, String mchId, String subMchId){
        ReconciliateLog rl = Pool.newInstance(ReconciliateLog.class, outTradeNo);
        rl.setResult(result);
        rl.setBillType(billType);
        rl.setPayTime(Timestamp.valueOf(payTime));
        rl.setExcType(excType);
        rl.setRemark(excType.getDesc());
        rl.setMchId(mchId);
        rl.setSubMchId(subMchId);
        // jdbcSession.insert(rl);
    }

    private String  generateDate(){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, -1);
        String time = (new SimpleDateFormat(
                "yyyyMMdd")).format(calendar.getTime());
        return time ;
    }*/

    /*@Override
    public void execute(JobExecutionContext context) {
        try {
            logger.info("***************start reconciliation,3 times every day,at 10,12,14 o'clock*************");
            reconciliationTask();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/




}
